<?php


namespace app\admin\model\express;


use addons\third\model\Third;
use EasyWeChat\Factory;
use think\Db;

class Subscribe
{
    protected $app = null;
    public function __construct()
    {
        $config = get_addon_config('third');
        $config = [
            'app_id'    => $config['wxapp']['app_id'],
            'secret'   => $config['wxapp']['app_secret'],
            'response_type' => 'array',
        ];
        $this->app = Factory::miniProgram($config);
    }

    public function push($user_id,$template_id,$page,$data){
        $openid = Third::where([
            'user_id' => $user_id,
            'platform' => 'wxapp',
        ])->value('openid');
        if(empty($openid)){
            return false;
        }
        $data = [
            'template_id' => $template_id, // 所需下发的订阅模板id
            'touser' => $openid,     // 接收者（用户）的  openid
            'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => $data,
            'miniprogram_state'=>"formal", //developer为开发版；trial为体验版；formal为正式版；
        ];
        $res = $this->app->subscribe_message->send($data);
        if(empty($res) || !is_array($res)){
            return false;
        }
        $nowTime = time();
        if(isset($res['errcode']) && $res['errcode'] != 0){
            $sub = model('app\api\model\TemplateSub')->where([
                'user_id' => $user_id,
                'template_id' => $template_id
            ])->count();
            if($sub){
                Db::name('express_template_sub')->where(["user_id"=>$user_id,'template_id'=>$template_id])->update(["status"=>0,'time'=>$nowTime]);
            }
            return $res;
        }

        $sub = model('app\api\model\TemplateSub')->where([
            'user_id' => $user_id,
            'template_id' => $template_id
        ])->find();
        if($sub){
            $status = ($sub->status - 1)>0?($sub->status - 1):0;
            Db::name('express_template_sub')->where(["user_id"=>$user_id,'template_id'=>$template_id])->update(["status"=>$status,'time'=>$nowTime]);
        }else{

        }

        return true;
    }
}
